const mongoose = require("mongoose");
const { User } = require("../models");
const crudUtil = require("./crudUtil/index");

//crud
const useradd = async (ctx, next) => {
  try {
    const { username, password } = ctx.request.body || {};
    if (!username || !password) {
      ctx.status = 400;
      ctx.body = { code: 400, message: "username 和 password 必须提供" };
      return;
    }

    // 检查是否存在
    const existing = await User.findOne({ username }).lean();

    if (existing) {
      ctx.body = { code: 300, message: "User already exists", data: existing };
      return;
    }

    // 创建用户（生产环境请对密码进行哈希）
    const created = await crudUtil.createUser(User, { username, password });

    ctx.body = { code: 200, message: "User added successfully", data: created };
  } catch (err) {
    ctx.status = 500;
    ctx.body = { code: 500, message: "Error adding user", error: err.message };
  }
};

const userupdate = async (ctx, next) => {
  try {
    const params = ctx.request.body || {};
    // ...updateFields → 剩余的所有字段放入一个新对象 updateFields
    const { _id, ...updateFields } = params;
    /**
     * !mongoose.Types.ObjectId.isValid(_id)
     *  mongoose.Types.ObjectId.isValid() 是 Mongoose 提供的方法
     *  用于判断一个字符串是否是 合法的 MongoDB ObjectId
     *  MongoDB ObjectId 格式：24 位十六进制字符，例如："6512abf3e1f23a456789abcd"
     */
    if (!_id || !mongoose.Types.ObjectId.isValid(_id)) {
      ctx.status = 400;
      ctx.body = { code: 400, message: "_id 必须为有效的 ObjectId" };
      return;
    }

    const res = await crudUtil.updateById(User, _id, updateFields);

    /**
       * 
       {
        acknowledged: true,  //表示数据库 成功接收到并执行了操作
        matchedCount: 1,     //表示 找到并匹配到的文档数量
        modifiedCount: 1,    //表示 实际被修改的文档数量
        upsertedId: null     //表示如果没有匹配的文档，则不会插入新文档。
      }

 */

    if (res.modifiedCount && res.modifiedCount > 0) {
      ctx.body = { code: 200, message: "User updated successfully", data: res };
    } else {
      ctx.body = { code: 300, message: "No changes made to the user" };
    }
  } catch (err) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: "Error updating user",
      error: err.message,
    };
  }
};

const userdel = async (ctx, next) => {
  try {
    const { _id } = ctx.request.body || {};
    if (!_id || !mongoose.Types.ObjectId.isValid(_id)) {
      ctx.status = 400;
      ctx.body = { code: 400, message: "_id 必须为有效的 ObjectId" };
      return;
    }

    const deleted = await crudUtil.deleteById(User, _id);
    if (deleted) {
      ctx.body = {
        code: 200,
        message: "User deleted successfully",
        data: deleted,
      };
    } else {
      ctx.body = { code: 300, message: "Failed to delete user" };
    }
  } catch (err) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: "Error deleting user",
      error: err.message,
    };
  }
};

const userfind = async (ctx, next) => {
  try {
    // 支持 query: page, limit, username (模糊)
    const result = await crudUtil.find(User, ctx.query || {});
    ctx.body = { code: 200, message: "Users retrieved", data: result };
  } catch (err) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: "Error finding users",
      error: err.message,
    };
  }
};

const findById = async (ctx, next) => {
  try {
    const { id } = ctx.params || {};
    if (!id || !mongoose.Types.ObjectId.isValid(id)) {
      ctx.status = 400;
      ctx.body = { code: 400, message: "id 必须为有效的 ObjectId" };
      return;
    }

    const doc = await crudUtil.findById(User, id);
    if (doc) {
      ctx.body = {
        code: 200,
        message: "User retrieved successfully",
        data: doc,
      };
    } else {
      ctx.body = { code: 300, message: "User not found" };
    }
  } catch (err) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: "Error retrieving user",
      error: err.message,
    };
  }
};

module.exports = {
  useradd,
  userupdate,
  userdel,
  userfind,
  findById,
};
